<?php
/**
 * Created by PhpStorm.
 * User: changshuiwang
 * Date: 2016/7/18
 * Time: 15:33
 */
namespace backend\controllers;

use common\models\Student;
use common\service\RedisCacheSrv;
use Yii;
use yii\base\Exception;
use yii\helpers\Json;
use yii\web\Controller;

class ApiController extends Controller
{
    /**
     * 
     * @id student id
     * @token 加密值
     */
    public $enableCsrfValidation = false;
    public function actionInfo()
    {
        try{
            if(Yii::$app->request->isPost){
                throw new \Exception("请求方式不合法",'3003');
            }else{
                $id=Yii::$app->request->getQueryParam("id");
                $token=Yii::$app->request->getQueryParam("token");
                $key=Yii::$app->params['key'];
                #$verify=md5($key.$id);
                $verify=11;
                if(empty($token) || $token!=$verify){
                    throw new \Exception("非法请求","3001");
                }
                $result=RedisCacheSrv::infoStuId($id);
                if(empty($result)){
                    $result=Student::findOne(['id'=>$id]);
                    if(empty($result)){
                        throw new \Exception('你请求的数据不存在','3002');
                    }else{
                        RedisCacheSrv::upStuId($id,$result);
                        return $this->successJson($result);
                    }
                }else{
                    return $this->successJson($result);
                }
            }
        }catch(\Exception $e){
            return $this->errorJson($e->getCode(),$e->getMessage());
        }
    }
    
    private function successJson($data,$message="success")
    {
        return Json::encode(array(
            'mes' => 'ok',
            'id' => $data['id'],
            'username' => $data['username'],
            'score' => $data['score'],
            'photo' => $data['photo'],
            'tag' => $data['tag']
        ));
    }

    private function errorJson($code,$mes)
    {
        return Json::encode(array(
            'code' => $code,
            'mes' => $mes
        ));
    }

    public function actionTest()
    {
/*        $result=Student::findOne(['id'=>13]);
        print_r($result);
        echo "<br/>";
        RedisCacheSrv::upStuId(13,$result);
        $result=RedisCacheSrv::infoStuId('13');
        print_r($result);
        echo "<br/>";*/
        
    }
}